<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\Article;
use App\Models\ArticleComments;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Login\UserController;

class CommentsController extends Controller
{
    //文章评论
    public function comments(Request  $request)
    {
        $param = $request->all();
        //定义验证规则
        $rules = [
            'article_id'    =>'required',
            'content'       => 'required',
//            'nickname'      => 'required',
        ];
        //定义报错信息
        $messages = [
            'article_id.required'   => '缺少文章不可为空',
            'content.required'      => '评论内容不可为空',
//            'nickname.required'        => '昵称不可为空',
        ];
        //将$res里面传过来的数据进行判断
        $validator =  Validator::make($param,$rules,$messages);
        //如果判断为真  就会跳到控制器error
        if ($validator->fails()){
            if(isset($validator->getMessageBag()->getMessages()['nickname'])){
                $error = $validator->getMessageBag()->getMessages()['nickname'][0];
            }else if(isset($validator->getMessageBag()->getMessages()['article_id'])){
                $error = $validator->getMessageBag()->getMessages()['article_id'][0];
            }else{
                $error = $validator->getMessageBag()->getMessages()['content'][0];
            }
            return response()->json([
                'code'=>0,
                'msg'=>$error,
                'data'=>[],
            ]);
        }

        //登录检查
        $user = session('user');
        if(!$user){
            return response()->json([
                'code'=>403,
                'msg'=>'请先登录!',
                'data'=>[],
            ]);
        }

        $article = Article::where('id',$param['article_id'])->first();
        $ins = [
            'category_id'=>$article->category_id,
            'article_id'=>$param['article_id'],
            'nickname'=>isset($user->nickname)?$user->nickname:$param['nickname'],
            'content'=>$param['content'],
            'date'=>date('Y-m-d'),
            'created_at'=>date('Y-m-d H:i:s'),
            'avatar'=>"/avatar/小人同而不和の唐红新.jpg",
        ];

        $result = DB::table('article_comments')->insert($ins);
        if($result){
            return response()->json([
                'code'=>1,
                'msg'=>"评论成功",
                'data'=>[],
            ]);
        }
        return response()->json([
            'code'=>0,
            'msg'=>"系统繁忙，请稍后再试！",
            'data'=>[],
        ]);



    }

}
